package org.example.B2;
import com.github.oxo42.stateless4j.StateMachine;
import com.github.oxo42.stateless4j.StateMachineConfig;

public class ControlPanel {
    private GuardCondition guardCondition = new GuardCondition();
    private StateMachine<State, Event> stateMachine;

    public ControlPanel(){
        init();
    }

    public void init() {
        guardCondition.setPassword("1234"); //设置密码
        guardCondition.setPasswordAttempts(0); //输入密码错误次数
        guardCondition.setInputPassword(""); //设置输入密码为空字符串
        guardCondition.setLockTime(0); //锁定开始时间

        StateMachineConfig<State, Event> config = new StateMachineConfig<>();

        /*
          定义状态转换规则
         */
        config.configure(State.Reading)
                .permitIf(Event.input, State.Comparing, guardCondition.inputLength_eq_4()) //,this::verifyPassword
                .ignoreIf(Event.input,guardCondition.inputLength_less_4());

        config.configure(State.Comparing)
                .permitIf(Event.passwordIncorrect,State.Reading, guardCondition.passwordAttempts_less_3(),new WrongPasswordless3())
                .permitIf(Event.passwordCorrect, State.Selecting,guardCondition.passwordCorrent(),new PasswordCorrectAction())
                .permitIf(Event.passwordIncorrect, State.Locked,guardCondition.passwordAttempts_to_3(),new LockedTimeOutAction())
                .ignore(Event.LockedtimeOut);

        config.configure(State.Locked)
                .permitIf(Event.LockedtimeOut, State.Reading,guardCondition.lockTimePass120s(),new LockedTimeOutAction())
                .ignoreIf(Event.LockedtimeOut, guardCondition.lockTimeNoPass120s());

        stateMachine = new StateMachine<>(State.Reading,config);
    }

    public void setLockTime(int lockTime){
        guardCondition.setLockTime(lockTime);
    }

    public int getLockTime(){
        return guardCondition.getLockTime();
    }

    public void setInputPassword(String inputPassword){
        guardCondition.setInputPassword(inputPassword);
    }
    public void setPasswordAttempts(int passwordAttempts){
        guardCondition.setPasswordAttempts(passwordAttempts);
    }
    public void fire(Event event){
        this.stateMachine.fire(event);
    }
    public State getCurrentState(){
        return this.stateMachine.getState();
    }
    public void printCurrentState() {
        System.out.println("当前状态: " + stateMachine.getState());
    }
}
